package com.xinxing.learning.security.config;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.xinxing.learning.security.filter.LoginFilter;
import com.xinxing.learning.security.service.CustomerUserDetailsService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.security.web.util.matcher.OrRequestMatcher;

import java.util.HashMap;

@Slf4j
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {

    private final CustomerUserDetailsService customerUserDetailsService;

    public SecurityConfig(CustomerUserDetailsService customerUserDetailsService) {
        this.customerUserDetailsService = customerUserDetailsService;
    }

    // @Bean
    // public UserDetailsService userDetailsService() {
    //     InMemoryUserDetailsManager inMemoryUserDetailsManager = new InMemoryUserDetailsManager();
    //     inMemoryUserDetailsManager.createUser(User.withUsername("root").password("{noop}123").roles("admin", "supper").build());
    //     return inMemoryUserDetailsManager;
    // }

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.userDetailsService(customerUserDetailsService);
    }

    @Override
    @Bean
    protected AuthenticationManager authenticationManager() throws Exception {
        return super.authenticationManager();
    }

    /**
     * 自定义filter
     * @return
     */
    @SneakyThrows
    @Bean
    public LoginFilter loginFilter() {
        LoginFilter loginFilter = new LoginFilter();
        loginFilter.setFilterProcessesUrl("/doLogin");
        loginFilter.setUsernameParameter("uname");
        loginFilter.setPasswordParameter("password");
        // 指定认证管理器
        loginFilter.setAuthenticationManager(authenticationManager());
        // 认证成功后的处理 返回处理成功的json
        loginFilter.setAuthenticationSuccessHandler((req, resp, authentication) -> {
            HashMap<String, Object> result = new HashMap<>();
            result.put("msg", "登录成功");
            result.put("status", HttpStatus.OK.value());
            result.put("authentication", authentication);
            resp.setContentType("application/json;charset=UTF-8");
            String resultStr = new ObjectMapper().writeValueAsString(result);
            log.info("onAuthenticationSuccess() returned: " + resultStr);
            resp.getWriter().println(resultStr);
        });
        // 认证失败后的处理 返回处理失败后的json
        loginFilter.setAuthenticationFailureHandler((req, resp, ex) -> {
            HashMap<String, Object> result = new HashMap<>();
            result.put("msg", "登录失败: " + ex.getMessage());
            result.put("status", HttpStatus.INTERNAL_SERVER_ERROR.value());
            String resultStr = new ObjectMapper().writeValueAsString(result);
            log.info("onAuthenticationFailure() returned: " + resultStr);
            resp.setContentType("application/json;charset=UTF-8");
            resp.getWriter().println(resultStr);
        });
        return loginFilter;
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        http.authorizeRequests()
                .anyRequest().authenticated()
                .and()
                .formLogin()
                .and()
                .exceptionHandling()
                .authenticationEntryPoint((req, resp, ex) -> {
                    HashMap<String, Object> result = new HashMap<>();
                    result.put("msg", "请先登录");
                    result.put("status", HttpStatus.UNAUTHORIZED.value());
                    resp.setContentType("application/json;charset=UTF-8");
                    String resultStr = new ObjectMapper().writeValueAsString(result);
                    log.info("onAuthenticationSuccess() returned: " + resultStr);
                    resp.getWriter().println(resultStr);
                })
                .and()
                .logout()
                // .logoutUrl("/logout")
                .logoutRequestMatcher(new OrRequestMatcher(
                        new AntPathRequestMatcher("/logout", "GET"),
                        new AntPathRequestMatcher("/logout", "POST")
                ))
                .logoutSuccessHandler((req, resp, authentication) -> {
                    HashMap<String, Object> result = new HashMap<>();
                    result.put("msg", "注销成功");
                    result.put("status", 200);
                    result.put("authentication", authentication);
                    resp.setContentType("application/json;charset=UTF-8");
                    String resultStr = new ObjectMapper().writeValueAsString(result);
                    log.info("onAuthenticationSuccess() returned: " + resultStr);
                    resp.getWriter().println(resultStr);
                })
                .and()
                .addFilterAt(loginFilter(), UsernamePasswordAuthenticationFilter.class)
                .csrf().disable()
        ;
    }
}
